package Chart;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.List;
import java.util.Map.Entry;
import java.util.ResourceBundle;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.util.ResourceBundleWrapper;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.ExtensionFileFilter;
import org.jfree.ui.RefineryUtilities;

@SuppressWarnings("serial")
public class PieChart extends ApplicationFrame implements ActionListener {

	// ten file lay tu open file
	static String filename = File.separator;
	private static String selectedPath;

	protected static ResourceBundle localizationResources = ResourceBundleWrapper
			.getBundle("org.jfree.chart.LocalizationBundle");

	/** A flag that controls whether or not file extensions are enforced. */
	private boolean enforceFileExtensions;

	static JRadioButtonMenuItem jVersion;
	static JRadioButtonMenuItem j30Minute;
	static JRadioButtonMenuItem j15Minute;
	static JRadioButtonMenuItem j5Minute;
	static JRadioButtonMenuItem j2Minute;
	static int statusButton = 0;

	public PieChart(String title) {
		super(title);
		setPreferredSize(new java.awt.Dimension(800, 600));

		JFileChooser fc = new JFileChooser(new File(filename));
		// init open action
		Action openAction = new OpenFileAction(this, fc);
		Action saveAction = new SaveFileAction(this, fc);

		// create menu bar
		JMenuBar mb = new JMenuBar();

		// create menu File
		JMenu jFile = new JMenu("File");
		mb.add(jFile);

		// create item menu File

		// create Open...
		JMenuItem jOpen = new JMenuItem(openAction);
		jFile.add(jOpen);
		jFile.addSeparator();

		// create Save As...
		JMenuItem jSave = new JMenuItem(saveAction);
		jFile.add(jSave);
		jFile.addSeparator();

		// create Exit
		JMenuItem jExit = new JMenuItem("Exit");
		jFile.add(jExit);
		jExit.addActionListener(this);

		// create menu Edit
		JMenu jEdit = new JMenu("Edit");
		mb.add(jEdit);

		// create item menu Edit

		// create Properties
		JMenuItem jProperties = new JMenuItem("Properties...");
		jEdit.add(jProperties);
		jProperties.addActionListener(this);

		// create menu View
		JMenu jView = new JMenu("View");
		mb.add(jView);

		// create item menu View

		// create Version
		jVersion = new JRadioButtonMenuItem("Version");
		jView.add(jVersion);
		jVersion.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getActionCommand().equals("Version")) {
					statusButton = 1;
					jVersion.setSelected(true);
					createPanel();
					j30Minute.setSelected(false);
					j15Minute.setSelected(false);
					j5Minute.setSelected(false);
					j2Minute.setSelected(false);
				}
			}
		});

		jView.addSeparator();
		// create Sub menu Time
		JMenu jTime = new JMenu("Time");
		jView.add(jTime);

		// create item sub menu

		// create 30 minute
		j30Minute = new JRadioButtonMenuItem("30 minute");
		jTime.add(j30Minute);
		j30Minute.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getActionCommand().equals("30 minute")) {
					statusButton = 2;
					j30Minute.setSelected(true);
					createPanel();
					jVersion.setSelected(false);
					j15Minute.setSelected(false);
					j5Minute.setSelected(false);
					j2Minute.setSelected(false);

				}

			}
		});

		// create 15 minute
		j15Minute = new JRadioButtonMenuItem("15 minute");
		jTime.add(j15Minute);
		j15Minute.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getActionCommand().equals("15 minute")) {
					statusButton = 3;
					j15Minute.setSelected(true);
					createPanel();
					jVersion.setSelected(false);
					j30Minute.setSelected(false);
					j5Minute.setSelected(false);
					j2Minute.setSelected(false);

				}
			}
		});

		// create 5 minute
		j5Minute = new JRadioButtonMenuItem("5 minute");
		jTime.add(j5Minute);
		j5Minute.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getActionCommand().equals("5 minute")) {
					statusButton = 4;
					j5Minute.setSelected(true);
					createPanel();
					jVersion.setSelected(false);
					j30Minute.setSelected(false);
					j15Minute.setSelected(false);
					j2Minute.setSelected(false);
				}
			}
		});

		// create 2 minute
		j2Minute = new JRadioButtonMenuItem("2 minute");
		jTime.add(j2Minute);
		j2Minute.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getActionCommand().equals("2 minute")) {
					statusButton = 5;
					j2Minute.setSelected(true);
					createPanel();
					jVersion.setSelected(false);
					j30Minute.setSelected(false);
					j15Minute.setSelected(false);
					j5Minute.setSelected(false);
				}
			}
		});

		this.setJMenuBar(mb);
		this.enforceFileExtensions = true;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getActionCommand().equals("Exit")) {
			Main demo = new Main("Demo");
			demo.pack();
			RefineryUtilities.centerFrameOnScreen(demo);
			demo.setVisible(true);
		} else if (e.getActionCommand().equals("Properties...")) {
			ChartPanel chartPanel = (ChartPanel) createPanel();
			chartPanel.doEditChartProperties();
		}
	}

	public void windowClosing(WindowEvent e) {
		Main demo = new Main("Demo");
		demo.pack();
		RefineryUtilities.centerFrameOnScreen(demo);
		demo.setVisible(true);
	}

	/**
	 * Creates a chart.
	 * 
	 * @param dataset
	 *            a dataset.
	 * 
	 * @return A chart.
	 */

	public static JFreeChart createChart(PieDataset dataset) {
		JFreeChart chart = ChartFactory.createPieChart("Pie Chart ", dataset,
				true, true, false);
		chart.setBackgroundPaint(Color.white);

		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setBackgroundPaint(Color.white);
		plot.setSectionOutlinesVisible(true);
		plot.setIgnoreZeroValues(true);
		plot.setIgnoreNullValues(true);
		plot.setCircular(true);

		plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
				"{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat
						.getPercentInstance()));
		plot.setNoDataMessage("No data available");

		return chart;
	}

	/**
	 * Creates a dataset version
	 * 
	 * @return the dataset.
	 */

	@SuppressWarnings("static-access")
	public static PieDataset createDataset() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		ReadData rd = new ReadData(selectedPath);
		if (selectedPath == null) {
			JFrame frame = new JFrame("Warning");
			JOptionPane.showMessageDialog(frame,
					" You can't show chart! Please click File/Open...!",
					"Warning", JOptionPane.WARNING_MESSAGE);
			jVersion.setSelected(false);
		} else if (jVersion.isSelected()) {
			rd.ReadofPieChart();
			for (Entry<String, Integer> entry : rd.dataPieChartVersion
					.entrySet()) {
				String key = entry.getKey();
				Integer value = entry.getValue();

				dataset.setValue(key, value);
			}
		}
		return dataset;
	}

	/**
	 * Creates a dataset Time
	 * 
	 * @return the dataset.
	 */

	@SuppressWarnings("static-access")
	public static PieDataset createDatasetTime1() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		ReadData rd = new ReadData(selectedPath);
		if (j30Minute.isSelected()) {
			if (selectedPath == null) {
				JFrame frame = new JFrame("Warning");
				JOptionPane.showMessageDialog(frame,
						" You can't show chart! Please click File/Open...!",
						"Warning", JOptionPane.WARNING_MESSAGE);
				j30Minute.setSelected(false);
			} else if (j30Minute.isSelected()) {

				rd.ReadofPieChart();
				for (Entry<String, List<Double>> entry : rd.dataPieChartTime1
						.entrySet()) {
					String key = entry.getKey();
					List<Double> value = entry.getValue();
					int sum = 0;
					for (@SuppressWarnings("unused")
					Double i : value) {
						sum++;
					}
					dataset.setValue(key, sum);
				}
			}
		}
		return dataset;
	}

	@SuppressWarnings("static-access")
	public static PieDataset createDatasetTime2() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		ReadData rd = new ReadData(selectedPath);
		if (j15Minute.isSelected()) {
			if (selectedPath == null) {
				JFrame frame = new JFrame("Warning");
				JOptionPane.showMessageDialog(frame,
						" You can't show chart! Please click File/Open...!",
						"Warning", JOptionPane.WARNING_MESSAGE);
				j15Minute.setSelected(false);
			} else if (j15Minute.isSelected()) {
				rd.ReadofPieChart();
				for (Entry<String, List<Double>> entry : rd.dataPieChartTime2
						.entrySet()) {
					String key = entry.getKey();
					List<Double> value = entry.getValue();
					int sum = 0;
					for (@SuppressWarnings("unused")
					Double i : value) {
						sum++;
					}
					dataset.setValue(key, sum);
				}
			}
		}
		return dataset;
	}

	@SuppressWarnings("static-access")
	public static PieDataset createDatasetTime3() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		ReadData rd = new ReadData(selectedPath);
		if (j5Minute.isSelected()) {
			if (selectedPath == null) {
				JFrame frame = new JFrame("Warning");
				JOptionPane.showMessageDialog(frame,
						" You can't show chart! Please click File/Open...!",
						"Warning", JOptionPane.WARNING_MESSAGE);
				j5Minute.setSelected(false);
			} else if (j5Minute.isSelected()) {
				rd.ReadofPieChart();
				for (Entry<String, List<Double>> entry : rd.dataPieChartTime3
						.entrySet()) {
					String key = entry.getKey();
					List<Double> value = entry.getValue();
					int sum = 0;
					for (@SuppressWarnings("unused")
					Double i : value) {
						sum++;
					}
					dataset.setValue(key, sum);
				}
			}
		}
		return dataset;
	}

	@SuppressWarnings("static-access")
	public static PieDataset createDatasetTime4() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		ReadData rd = new ReadData(selectedPath);
		if (j2Minute.isSelected()) {
			if (selectedPath == null) {
				JFrame frame = new JFrame("Warning");
				JOptionPane.showMessageDialog(frame,
						" You can't show chart! Please click File/Open...!",
						"Warning", JOptionPane.WARNING_MESSAGE);
				j2Minute.setSelected(false);
			} else if (j2Minute.isSelected()) {
				rd.ReadofPieChart();
				for (Entry<String, List<Double>> entry : rd.dataPieChartTime4
						.entrySet()) {
					String key = entry.getKey();
					List<Double> value = entry.getValue();
					int sum = 0;
					for (@SuppressWarnings("unused")
					Double i : value) {
						sum++;
					}
					dataset.setValue(key, sum);
				}
			}
		}
		return dataset;
	}

	/**
	 * Creates a panel for the demo (used by SuperDemo.java).
	 * 
	 * @return A panel.
	 */
	public JPanel createPanel() {
		PieDataset dataset = null;
		switch (statusButton) {
		case 1:
			dataset = createDataset();
			break;
		case 2:
			dataset = createDatasetTime1();
			break;
		case 3:
			dataset = createDatasetTime2();
			break;
		case 4:
			dataset = createDatasetTime3();
			break;
		default:
			dataset = createDatasetTime4();
			break;
		}

		JFreeChart chart = createChart(dataset);
		ChartPanel chartPanel = new ChartPanel(chart);
		chartPanel.setPreferredSize(new java.awt.Dimension(800, 600));
		chartPanel.setMouseZoomable(true, false);
		setContentPane(chartPanel);
		SwingUtilities.updateComponentTreeUI(getLayeredPane());
		return chartPanel;
	}

	// class create open file action
	class OpenFileAction extends AbstractAction {

		JFrame frame;
		JFileChooser chooser;

		public OpenFileAction(JFrame frame, JFileChooser chooser) {
			super("Open...");
			this.chooser = chooser;
			this.frame = frame;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals("Cancel")) {
				selectedPath = null;
			} else {
				// Show dialog; this method does not return until dialog is
				// closed
				int option = chooser.showOpenDialog(frame);
				if (option == JFileChooser.APPROVE_OPTION) {

					// Get the selected file
					selectedPath = chooser.getSelectedFile().getPath();
				}
			}
		}
	}

	public boolean isEnforceFileExtensions() {
		return this.enforceFileExtensions;
	}

	class SaveFileAction extends AbstractAction {

		JFrame jFrame;
		JFileChooser chooser;
		private File defaultDirectoryForSaveAs;

		public SaveFileAction(JFrame jFrame, JFileChooser chooser) {
			super("Save As...");
			this.jFrame = jFrame;
			this.chooser = chooser;
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			chooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
			ExtensionFileFilter filter = new ExtensionFileFilter(
					((ResourceBundle) localizationResources)
							.getString("PNG_Image_Files"), ".png");
			chooser.addChoosableFileFilter(filter);

			PieDataset dataset = null;
			if (jVersion.isSelected()) {
				dataset = createDataset();
			} else if (j30Minute.isSelected()) {
				dataset = createDatasetTime1();
			} else if (j15Minute.isSelected()) {
				dataset = createDatasetTime2();
			} else if (j5Minute.isSelected()) {
				dataset = createDatasetTime3();
			} else if (j2Minute.isSelected()) {
				dataset = createDatasetTime4();
			}

			JFreeChart chart = createChart(dataset);

			int option = chooser.showSaveDialog(jFrame);
			if (option == JFileChooser.APPROVE_OPTION) {
				String filename = chooser.getSelectedFile().getPath();
				if (isEnforceFileExtensions()) {
					if (!filename.endsWith(".png")) {
						filename = filename + ".png";
					}
				}
				try {
					ChartUtilities.saveChartAsPNG(new File(filename), chart,
							getWidth(), getHeight());
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}